package com.nervenets.web.service;

import com.nervenets.Global;
import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.PropertiesLoader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class MailService {
    @Resource
    JavaMailSender mailSender;

    public void sendExceptions(String title, String exceptions, String filePath) {
        sendEmail("285282005@qq.com", String.format("%s系统异常：%s", title, JodaUtils.timeLongToString()), exceptions, filePath);
    }

    public void sendEmail(String to, String title, String content, String filePath) {
        MimeMessage mimeMessage;
        try {
            mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            final PropertiesLoader propertiesLoader = Global.getApplicationProperties();
            helper.setFrom(new InternetAddress("胜券网活动 <" + propertiesLoader.getProperty("spring.mail.username") + ">"));
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(content, true);
            if (null != filePath) {
                //注意项目路径问题，自动补用项目路径
                FileSystemResource file = new FileSystemResource(new File(filePath));
                //加入邮件
                helper.addAttachment(filePath, file);
            }

            mailSender.send(mimeMessage);
            System.out.println(to + "邮件发送成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
